<?php

/**
 * 消息
 */
class messageModel {

    public function __construct(& $base)
    {
        $this->base = $base;

        !$this->base->im && $this->base->in_im();
        $this->im = & $this->base->im;
    }


    /**
     * 获取所有未发送的消息
     * @return [type] [description]
     */
    public function findAllMessageByIsSend(){
        return $this->base->db->getAll("select * from r_message_record where is_send = 0 and is_before = 0");
    }

    /**
     * 查询消息
     * @param  integer $category [消息类别]
     * @param  integer $startId  [消息ID]
     * @param  integer $count    [消息数量]
     * @return [type]            [description]
     */
    public function findMessage($category = 1,$startId = 0, $count = 100){
        if(0 == $startId){
            $sql = "select * from r_message_record where is_send = 1 and  category = '" . $category . "' and target_id = '" . $this->base->uid . "' order by id desc limit " . $count;
        }else{
            $sql = "select * from r_message_record where is_send = 1 and is_read = 0 and category = '" . $category . "' and id >'" . $startId . "' and target_id = '" . $this->base->uid . "'  order by id desc limit " . $count;
        }
        return $this->base->db->getAll($sql);
    }

    /**
     * 新增消息
     * @param  [type] $category    [消息类别(跑步有道、新的朋友、群组)]
     * @param  [type] $send_id     [消息代发送者ID(跑步有道账户ID、新的朋友账户ID、群组账户ID)]
     * @param  [type] $source_id   [消息主体ID(好友添加者ID、被添加者ID、群组ID、帖子评论者ID)]
     * @param  [type] $target_id   [消息接收者ID(被添加者ID、群组成员ID、帖子发布者ID、帖子回复者ID)]
     * @param  [type] $content     [消息内容(纯内容、跑步有道的JSON消息内容)]
     * @param  [type] $is_send     [是否已发送 0否1是]
     * @param  [type] $is_read     [是否已读 0否1是]
     * @param  [type] $type        [消息类型(0通知、1操作类型)]
     * @param  [type] $status      [消息状态(这里针对操作类型消息,0为待操作、1已操作)]
     * @param  [type] $status_time [消息状态操作时间]
     * @return [type]              [消息产生时间]
     */
    public function insertMessage($category, $send_id ,$source_id ,$target_id ,$descType, $content , $type = 0 ,$is_send = 0,$is_read = 0,$status = 0,$status_time = ''){
        $time = time();

        //检查接收用户的客户端版本,如果小于2.4的话,不会发送消息
        $is_before = 0;
        $clientInfo = $this->base->load('client')->getClientInfoByUid($target_id);
        if(!empty($clientInfo) && isset($clientInfo['version']) && intval($clientInfo['version']) < 2400){
            $is_before = 1;
        }
        $is_send = 1;
        $info = compact('category', 'send_id', 'source_id', 'target_id','descType','content','is_send','is_read','type','status','status_time','time','is_before');
        //return $this->base->db->insertRowTable('r_message_record',$info);
        $rst = $this->base->db->insertRowTable('r_message_record',$info);

        if($rst){
            if(0 == $is_before){
                $info['id'] = $rst;
                $this->sendMsg($info);
            }
        }
    }

    /**
     * 将消息更新为已读的状态 
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function updateMessageByIsRead($id){
        return $this->base->db->update("update r_message_record set is_read = '1' where id = '" . $id . "'");
    }

    /**
     * 更新操作类型消息状态
     * @param  [type] $categroy  [description]
     * @param  [type] $source_id [description]
     * @param  [type] $target_id [description]
     * @return [type]            [description]
     */
    public function updateMessageByStatus($categroy, $source_id,$target_id, $desc, $status){
        //类型为新的朋友或群组,并且根据操作者ID、接收者ID、已发送的、类型为操作型的、状态是请求同意的 条件操作
        $sql = "update r_message_record set status = ".$status." , status_time = '".time()."' where category = '".$categroy."' and source_id = '".$source_id."' and target_id = '".$target_id."' and descType = '" . $desc . "' and is_send = 1 and type = 1 and status  in (0,2) ";
        $this->loginfo($sql);
        $rst = $this->base->db->update($sql);
    }

    private function loginfo($content, $fileName = 'log', $folder = 'sql'){
        //文件所处目录
        $path = $this->base->config['log-dir'] . $folder . "/";
        //查看文件目录是否存在,不存在创建
        !file_exists($path) && mkdir($path);
        //文件名称及类型
        $logName = $fileName.'.txt';
        //写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。
        $fp = fopen($path.$logName, "a");
        //文件内容前缀
        $log_prefix = '---start---'.date('Y-m-d H:i:s')."---\n";
        //文件内容后缀
        $log_suffix = '---end---'.date('Y-m-d H:i:s')."---\n";
        //写入内容
        fwrite($fp, $log_prefix . $content . "\n" . $log_suffix);
        //写入换行
        fwrite($fp, "\n");
        //关闭
        fclose($fp);
    }

    /**
     * 删除消息
     * @param  [type] $mId [description]
     * @return [type]      [description]
     */
    public function deleteMessage($mId){
        return $this->base->db->delDataTable('r_message_record'," id = '" . $mId . "'");
    }

    /**
     * 获取消息内容描述
     * @param  [type] $key   [描述Key]
     * @param  array  $param [内容填充参数]
     * @return [type]        [description]
     */
    public function getContentDesc($key, $param = array()){

        $desc = array(
            "F1" => "添加你为好友",
            "F2" => "我通过了你的好友验证请求，现在我们可以开始聊天了",

            "N1" => "喜欢了你的帖子: %s",
            "N2" => "回复了你的帖子: %s",
            "N3" => "点亮了你的回复: %s",
            "N4" => "回复了你的回复: %s",
            "N5" => "评论了你的活动：%s",
            "N6" => "回复了你的回复：%s",
            "N7" => "置顶了你的帖子 %s",
            "N8" => "你的帖子：%s 被删除",
            "N9" => "%s",
            "N10" => "赐予你%s点正能量以示鼓励！",
            "N11" => "在以下跑友秀中提到了你，去看看吧",

            "G1" => "%s 申请加入群组 %s",
            "G2" => "%s 同意你加入该群组",
            "G3" => "%s 邀请你加入",//群主、管理员邀请
            "G4" => "%s 同意你的邀请",
            "G5" => "%s 已退出群组",
            "G6" => "%s 将你移除群组",
            "G7" => "群主 %s 将群组解散，同时群所有活动已取消",
            "G8" => "%s 将你设置为管理员",
            "G9" =>"你已被 %s 取消管理员",
            "G10" => "%s 邀请你加入",//普通成员邀请
            "G11" => "%s 参加了 %s", //通知群组有人参加群组活动
            "G12" => "你已加入该群", //不需要审核直接加入
            "G13" => "%s 取消了 %s",//群组取消了活动
            "G14" => "%s 已退出 %s",//退出活动
            "G15" => "%s 想要参加 %s 快去认领吧",//活动认领
            "G16" => "已经有 %s 成员参加了 %s",//成员参加了活动
            "G17" => "你参加的 %s 马上就要开始了，做好准备一起happy吧",//活动开始前2小时
            "G18" => "你参加的 %s 已经结束了，看看小伙伴的运动情况吧",//竞赛活动结束
            "G19" => "%s 将 %s 转让给你，您现在是群主",//转让
            "G20" => "您希望参与的 %s 已被群主关闭，您可以参与其他群组的此次官方活动",//关闭官方活动
            "G21" => "%s 发布了 %s 快快参加吧",//创建活动
            "G22" => "你已被 %s 移除 %s",//被退出活动
            "G23" => "你已经参与 %s",//通知当事人他已参加活动
            "G24" => "你已退出 %s",//退出活动
        );
        if($this->base->vn >= 2800){
            $desc['N1'] = "喜欢了你的%s";
            $desc['N2'] = "评论了你发布的%s：%s";
            $desc['N3'] = "点亮了你的评论：%s";
            $desc['N4'] = "回复了你的评论：%s";
        }

        return array_key_exists($key, $desc) ? isset($desc[$key]) ? vsprintf($desc[$key],$param) : "" : "";
    }


    public function getPushContentDesc($data){
        $descType = $data['descType'];

        switch ($descType) {
            case 'F1':
                $sourceUserInfo = $this->base->load('client')->getUserInfo($data['source_id']);
                $userName = empty($sourceUserInfo) ? "有人" : (!isset($sourceUserInfo['nickname']) ? "有人" : $sourceUserInfo['nickname']);
                $desc = "%s 添加你为好友";
                return vsprintf($desc,array($userName));
                break;
            case 'F2':
                $targetUserInfo = $this->base->load('client')->getUserInfo($data['source_id']);
                $userName = empty($targetUserInfo) ? "有人" : (!isset($targetUserInfo['nickname']) ? "有人" : $targetUserInfo['nickname']);
                
                $desc = "%s 同意添加你为好友";
                return vsprintf($desc,array($userName));
                break;
            case 'N1':
                return "你的帖子被点赞啦！";
                break;
            case 'N2': //评论帖子
                return "你的帖子有了新评论";
                break;
            case 'N3':
                return "你的帖子被点亮";
                break;
            case 'N4': //回复评论
                return "你的评论有了新回复";
                break;
            case "N5":
                return "你有一条消息";
                break;
            case "N6":
                return "回复了你的评论";
                break;
            case "N7":
                return "你有一条帖子消息";
                break;
            case "N8":
                return "你有一条帖子消息";
                break;
            case "N9": //跑步有道消息推送
                $arr = json_decode($data['content'], true);
                $newInfo = $this->base->load('news')->getRawNewsInfo($arr['news_id']);
                return $newInfo['title'];
                break;
            case "N10": //帖子正能量打赏
                return "你的帖子获得了正能量";
                break; 
            case "N11":
                return "在以下跑友秀中提到了你，去看看吧";
                break;
            case 'G1':
                $arr = json_decode($data['content'],true);
                $targetUserInfo = $this->base->load('client')->getUserInfo($arr['oper_id']);
                $userName = empty($targetUserInfo) ? "有人" : (!isset($targetUserInfo['nickname']) ? "有人" : $targetUserInfo['nickname']);
                
                $groupInfo = $this->base->load('group')->getGroupInfo($data['source_id']);
                $groupName = empty($groupInfo) ? "该群" : (!isset($groupInfo['name']) ? "该群"  : $groupInfo['name']);
                
                $desc = "%s 申请加入 %s";
                return vsprintf($desc,array($userName, $groupName));
                break;
            case 'G2':
                $groupInfo = $this->base->load('group')->getGroupInfo($data['source_id']);

                $groupName = empty($groupInfo) ? "该群" : (!isset($groupInfo['name']) ? "该群"  : $groupInfo['name']);

                $desc = "你加入 %s 申请已被通过";
                return vsprintf($desc,array($groupName));
                break;
            case 'G3':
                $arr = json_decode($data['content'],true);
                $operUserInfo = $this->base->load('client')->getUserInfo($arr['oper_id']);
                $userName = empty($operUserInfo) ? "有人" : (!isset($operUserInfo['nickname']) ? "有人" : $operUserInfo['nickname']);

                $groupInfo = $this->base->load('group')->getGroupInfo($data['source_id']);
                $groupName = empty($groupInfo) ? "该群" : (!isset($groupInfo['name']) ? "该群"  : $groupInfo['name']);

                $desc = "%s 邀请你加入 %s";
                return vsprintf($desc,array($userName, $groupName));
                break;
            case 'G4':
                return "你有一条群组消息";
                break;
            case 'G5':
                return "你有一条群组消息";
                break;
            case 'G6':
                return "你有一条群组消息";
                break;
            case 'G7':
                return "你有一条群组消息";
                break;
            case 'G8':
                $desc = "你已被设置为 %s 管理员";
                break;
            case 'G9':
                return "你有一条群组消息";
                break;
            case 'G10':
                $arr = json_decode($data['content'],true);
                $operUserInfo = $this->base->load('client')->getUserInfo($arr['oper_id']);
                $userName = empty($operUserInfo) ? "有人" : (!isset($operUserInfo['nickname']) ? "有人" : $operUserInfo['nickname']);

                $groupInfo = $this->base->load('group')->getGroupInfo($data['source_id']);
                $groupName = empty($groupInfo) ? "该群" : (!isset($groupInfo['name']) ? "该群"  : $groupInfo['name']);

                $desc = "%s 邀请你加入 %s";
                return vsprintf($desc,array($userName, $groupName));
                break;
            default:
                return "你有一条群组消息";
                break;
        }
    }

    /**
     * 转换数据格式
     * @param  [type] $category [description]
     * @param  [type] $data     [description]
     * @return [type]           [description]
     */
    public function convertMessageContent($category,$data){
        
        $all = array();
        foreach ($data as $key => $value) {
            $item = array();
            switch ($category) {
                case '1':
                    $item = $this->convertFriendMessageContent($value);
                    break;
                case '2':
                    $item = $this->convertNewsMessageContent($value);
                    break;
                case '3':
                    $item = $this->convertGroupMessageContent($value);
                    break;
            }
            array_push($all, $item);
        }


        return array("category"=>$category,"detail"=>$all);
    }

    /**
     * 转换新的朋友数据格式
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function convertFriendMessageContent($data){
        $arr = json_decode($data['content'],true);
        $content = $this->getContentDesc($data['descType'],array());

        $userInfo = $this->base->load('client')->getUserInfo($data['source_id']);
        //$userName = $userInfo['nickname'];
        //$userHeader = $userInfo['header'];

        $userName = empty($userInfo) ? "热心人" : !isset($userInfo['nickname']) ? "热心人" : $userInfo['nickname'];
        $userHeader = empty($userInfo) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : !isset($userInfo['header']) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : $userInfo['header'];

        $item = array(
            "id" => $data['id'],
            "user_id" => $data['source_id'],
            "user_name" => $userName,
            "user_header" => $userHeader,
            "target_id" => $data['target_id'],
            "descType" => $data['descType'],
            "content" => $content,
            "type" => $data['type'],
            "status" => $data['status'],
            "status_time" => $data['status_time'],
            "time" => $data['time']
        );
        return $item;
    }

    /**
     * 转换跑步有道数据格式
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function convertNewsMessageContent($data){
        $arr = json_decode($data['content'],true);
        $userInfo = $this->base->load('client')->getUserInfo($data['source_id']);
        //$userName = $userInfo['nickname'];
        //$userHeader = $userInfo['header'];
        $newsInfo = $this->base->load('news')->getNewsInfo($arr['news_id']);
        $uid = $this->base->redis->hget(REDIS_PREFIX."NewsInfo_".$arr['news_id'],'uid');
        if(!empty($uid)){
            $postUser = $this->base->load('client')->getUserInfo($uid);
            $postUserName = isset($postUser['nickname']) ? $postUser['nickname'] : '热心人' ;
        }else{
            $postUserName = "热心人";
        }
        $thumb_img = json_decode($this->base->redis->hget(REDIS_PREFIX. 'NewsInfo_' . $arr['news_id'],'thumb_img'),true);

        $postImg = isset($thumb_img[0]) ? $thumb_img[0] : '';
        $title = !empty($newsInfo['title']) ? $newsInfo['title'] : (!empty($newsInfo['short_desc']) ? $newsInfo['short_desc'] : '神秘的帖子');
        $userName = empty($userInfo) ? "热心人" : !isset($userInfo['nickname']) ? "热心人" : $userInfo['nickname'];
        $userHeader = empty($userInfo) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : !isset($userInfo['header']) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : $userInfo['header'];
        $atype = "-1";

        $aid = 0;
        $aTitle = '';
        $aImg = '';

        if(!empty($arr['gid']) && !empty($arr['news_id']))
        {
            $aid = $arr['news_id'];
            $actInfo = $this->base->load('groupActivity')->getActByAid($arr['news_id']);

            if(!empty($actInfo['title']))
            {
                $aTitle = $actInfo['title'];
                $aImg = !empty($actInfo['img']) ? $actInfo['img'] : '';
            }
            else
            {
                $actInfo['title'] = '';
                $actInfo['img'] = '';
                $actInfo['type'] = '';
            }
        }

        if("N4" == $data['descType'] || "N3" == $data['descType']){
            $commentContent = $this->base->load('news')->getNewsComment($arr['comment_id']);
            $content = $this->getContentDesc($data['descType'],array($commentContent));
        }

        if( "N7" == $data['descType'] || "N8" == $data['descType']){
            $content = $this->getContentDesc($data['descType'],array($title));
        }
        if($this->base->vn >= 2800){
            $sourceMap = ['showtime'=>"跑友秀",'hotans'=>"问答","groupNews"=>"群空间"];
            $source = isset($arr['source']) && !empty($arr['source']) ? $arr['source'] : 'showtime';
            $source = $sourceMap[$source];
            if("N1" == $data['descType']){
                $content = $this->getContentDesc($data['descType'],array($source));
            }
            if("N2" == $data['descType']){
                $content = $this->getContentDesc($data['descType'],array($source,$arr['content']));
            }
        }elseif("N2" == $data['descType'] || "N1" == $data['descType']){
            $content = $this->getContentDesc($data['descType'],array($title));
        }
        if("N5" == $data['descType']){
            $content = $this->getContentDesc($data['descType'],array($actInfo['title']));
            $atype = intval($actInfo['type']);
        }
        if("N6" == $data['descType']){
            $commentContent = $this->base->load('groupActivity')->getContent($arr['comment_id']);
            $content = $this->getContentDesc($data['descType'],array($commentContent));
            $atype = intval($actInfo['type']);
        }
        if("N9" == $data['descType']){
            $content = $this->getContentDesc($data['descType'],array($title));
        }
        if("N10" == $data['descType']){
            $content = $this->getContentDesc($data['descType'],array($arr['energy']));
        }
        if("N11" == $data['descType']){
            $content = $this->getContentDesc($data['descType']);
        }
        $item = array(
            "id" => $data['id'],
            "user_id" => $data['source_id'],
            "user_name" => $userName,
            "user_header" => $userHeader,
            "target_id" => $data['target_id'],
            "news_id" => $arr['news_id'],
            "comment_id" => isset($arr['comment_id']) ? $arr['comment_id'] : 0,
            "descType" => $data['descType'],
            "desc" => $arr['content'],
            "content" => $content,
            "type" => $data['type'],
            'atype' => $atype,
            "status" => $data['status'],
            "status_time" => $data['status_time'],
            "time" => $data['time'],
            'gid' => isset($arr['gid']) ? $arr['gid'] : 0,
            'postUserId' => $data['target_id'],//发帖人ID
            'postUserName'=> $postUserName,//发帖人昵称
            'postImg' => $postImg,//帖子图片
            'title' => $title,//帖子标题
            'aid' => $aid,
            'atitle' => $aTitle,
            'aimg' => $aImg
        );
        return $item;
    }

    /**
     * 转换群组数据格式
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function convertGroupMessageContent($data){
        $arr = json_decode($data['content'],true);
        $this->loginfo($arr['oper_id']);
        $userInfo = $this->base->load('client')->getUserInfo($arr['oper_id']);
        $this->loginfo(var_export($userInfo,true));
        $userName = empty($userInfo) ? "热心人" : !isset($userInfo['nickname']) ? "热心人" : $userInfo['nickname'];
        $userHeader = empty($userInfo) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : !isset($userInfo['header']) ? "http://irun.hupu.com/static/bootstrap/img/jog_logo.png" : $userInfo['header'];

        $groupInfo = $this->base->load('group')->getGroupInfo($data['source_id']);
        $groupName = isset($groupInfo['name']) ? $groupInfo['name'] : "该群";
        $groupHeader = isset($groupInfo['header']) ? $groupInfo['header'] : '';
        $actInfo = !empty($arr['aid']) ? $this->base->load('groupActivity')->getActByAid($arr['aid']) : [];
        $actTitle = !empty($actInfo['title']) ? $actInfo['title'] : '';
        $actImg = !empty($actInfo['banner']) && is_array($actInfo['banner']) ? $actInfo['banner'][0] : '';
        $atype = "-1";
        switch($data['descType']){
            case "G1":
                $reason = isset($arr['reason']) ? $arr['reason'] : "";
                $content = $this->getContentDesc($data['descType'],array($userName,$reason));
                break;
            case "G11":
            case "G13":
            case "G14":
            case "G15":
            case "G22":
                $title = empty($actInfo['title']) ? "活动" : $actInfo['title'];
                $content = $this->getContentDesc($data['descType'],array($userName,$title));
                $atype = intval($actInfo['type']);
                break;
            case "G17":
            case "G18":
                $title = empty($actInfo['title']) ? "活动" : $actInfo['title'];
                $content = $this->getContentDesc($data['descType'],array($title));
                $atype = intval($actInfo['type']);
                break;
            case "G12":
                $content = $this->getContentDesc($data['descType']);
                break;
            case "G19":
                $content = $this->getContentDesc($data['descType'],array($userName,$groupName));
                break;
            case "G20":
            case "G23":
            case "G24":
                $title = empty($actInfo['title']) ? "活动" : $actInfo['title'];
                $content = $this->getContentDesc($data['descType'],array($title));
                $atype = intval($actInfo['type']);
                break;
            case "G21":
                $title = empty($actInfo['title']) ? "活动" : $actInfo['title'];
                $content = $this->getContentDesc($data['descType'],array($groupName,$title));
                $atype = intval($actInfo['type']);
                break;
            default:
                $content = $this->getContentDesc($data['descType'],array($userName));
        }

        $item = array(
            "id" => $data['id'],
            "group_id" => $data['source_id'],
            "group_name" => $groupName,
            "group_header" => $groupHeader,
            "target_id" => $arr['oper_id'],
            "target_role" => $arr['target_role'],
            "content" => $content,
            "descType" => $data['descType'],
            "type" => $data['type'],
            "status" => $data['status'],
            "status_time" => $data['status_time'],
            "time" => $data['time'],
            "g_add_id" => isset($arr['g_add_id']) ? $arr['g_add_id'] : "",
            "aid" => isset($arr['aid']) ? $arr['aid'] : 0,
            "aimg" => $actImg,
            "atitle" => $actTitle,
            "atype" => $atype
        );
        return $item;
    }
    
    /**
     * 检查重复发送消息
     * @param  [array] $data [消息数据]
     * @return [bool]       [是否重复;true代表重复,false代表未重复]
     */
    public function  checkRepeatSendMessage($data)
    {

        //"F1" => "添加你为好友",
        //无需
        
        //"F2" => "我通过了你的好友验证请求，现在我们可以开始聊天了",
        //无需

        // "N1" => "喜欢了你的帖子: %s",
        // 无需
        // 
        // "N2" => "回复了你的帖子: %s",
        // 无需
        // 
        // "N3" => "点亮了你的回复: %s",
        // 无需
        // 
        // "N4" => "回复了你的回复: %s",
        //无需

        //"G1" => "%s 申请加入群组",
        //群组ID、目标接收人ID(群主和管理员)、消息类型、操作人 保持唯一
        //
        //"G2" => "%s 通过你的加入申请",
        //无需        
        //
        //"G3" => "%s 邀请你加入",//群主、管理员邀请
        //群组ID、目标接收人ID、消息类型、操作人(群主、管理员) 保持唯一
        //
        //"G4" => "%s 同意你的邀请",
        //无需
        //
        //"G5" => "%s 已退出群组",
        //无需
        //
        //"G6" => "%s 将你移除群组",
        //无需
        //
        //"G7" => "群主 %s 将群组解散",
        //无需
        //
        //"G8" => "%s 将你设置为管理员",
        //无需
        //"G9" =>"你已被 %s 取消管理员",
        //无需
        //
        //"G10" => "%s 邀请你加入",//普通成员邀请
        //群组ID、目标接收人ID、消息类型、操作人(普通成员) 保持唯一
        //
            
        $descType = isset($data['descType']) && !empty($data['descType']) ? $data['descType'] : "";
        switch ($descType) {
            case 'G1':
                return $this->isRepeatMessage($data['source_id'],$data['target_id'],$data['descType'],$data['oper_id']);
                break;
            case 'G3':
                return $this->isRepeatMessage($data['source_id'],$data['target_id'],$data['descType'],$data['oper_id']);
                break;
            case 'G10':
                return $this->isRepeatMessage($data['source_id'],$data['target_id'],$data['descType'],$data['oper_id']);
                break;
        }
        return false;
    }


    public function isRepeatMessage($group_id, $target_id, $descType, $oper_id)
    {
        $sql = "select content from r_message_record where source_id = '" . $group_id . "' and target_id = '" . $target_id . "' and descType = '" . $descType . "' ";
        $result = $this->base->db->getAll($sql);
        foreach ($result as $key => $value) {
            $content = json_decode($value['content'],true);
            if(is_array($content)){
                $con_oper_id = isset($content['oper_id']) && !empty($content['oper_id']) ? $content['oper_id'] : "";
                if($con_oper_id == $oper_id){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 添加消息同步(二人会话、群聊数据)
     * @param [type] $data [description]
     */
    public function addMessageSync($data){
        $fromUserId = isset($data['fromUserId']) ? $data['fromUserId'] : "";
        $toUserId = isset($data['toUserId']) ? $data['toUserId'] : "";
        $objectName = isset($data['objectName']) ? $data['objectName'] : "";
        $content = isset($data['content']) ? $data['content'] : "";
        $timestamp = isset($data['timestamp']) ? $data['timestamp'] : "";
        $channelType = isset($data['channelType']) ? $data['channelType'] : "";
        $info = compact('fromUserId', 'toUserId', 'objectName','content','timestamp','channelType');

        $this->base->db->insertRowTable('r_message_sync',$info);
        $this->sendInstrTriggerMessage($toUserId, $fromUserId, $objectName, $content);
    }

    /**
     * 获取广播的消息
     * @return [type] [description]
     */
    public function getBroadcastMessage(){
        //获取所有未发送的广播消息
        return $this->base->db->getAll("select * from r_message_broadcast");
    }


    /**
     * 获取 Token 方法
     * @param  [type] $userId      [用户 Id，最大长度 32 字节。是用户在 App 中的唯一标识码，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。]
     * @param  [type] $name        [用户名称，最大长度 128 字节。用来在 Push 推送时，或者客户端没有提供用户信息时，显示用户的名称。]
     * @param  [type] $portraitUri [用户头像 URI，最大长度 1024 字节。]
     * @return [type]              [description]
     */
    public function getToken($userId,$name,$portraitUri){
        return $this->format_array($this->im->getToken($userId,$name,$portraitUri));
    }

    /**
     * 刷新用户信息 方法  说明：当您的用户昵称和头像变更时，您的 App Server应该调用此接口刷新在融云侧保存的用户信息，以便融云发送推送消息的时候，能够正确显示用户信息
     * @param  [type] $userId      [用户 Id，最大长度 32 字节。是用户在 App 中的唯一标识码，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。（必传）]
     * @param  string $name        [用户名称，最大长度 128 字节。用来在 Push 推送时，或者客户端没有提供用户信息时，显示用户的名称。]
     * @param  string $portraitUri [用户头像 URI，最大长度 1024 字节]
     * @return [type]              [description]
     */
    public function userRefresh($userId,$name='',$portraitUri=''){
        return $this->format_array($this->im->userRefresh($userId,$name,$portraitUri));
    }

    /**
     * 检查用户在线状态 方法
     * @param  [type] $userId [用户 Id。（必传）]
     * @return [type]         [description]
     */
    public function userCheckOnline($userId){
        return $this->format_array($this->im->userCheckOnline($userId));
    }

    /**
     * 封禁用户 方法
     * @param  [type] $userId [用户 Id。（必传）]
     * @param  [type] $minute [封禁时长,单位为分钟，最大值为43200分钟。（必传）]
     * @return [type]         [description]
     */
    public function userBlock($userId,$minute){
        return $this->format_array($this->im->userBlock($userId,$minute));
    }

    /**
     * 解除用户封禁 方法
     * @param  [type] $userId [用户 Id。（必传）]
     * @return [type]         [description]
     */
    public function userUnBlock($userId){
        return $this->format_array($this->im->userUnBlock($userId));
    }

    /**
     * 获取被封禁用户 方法
     * @return [type] [description]
     */
    public function userBlockQuery(){
        return $this->format_array($this->im->userBlockQuery());
    }

    /**
     * 向融云服务器提交 userId 对应的用户当前所加入的所有群组。
     * @param  [type] $userId [被同步群信息的用户Id。（必传）]
     * @param  array  $data   [该用户的群信息。（必传）array('key'=>'val')]
     * @return [type]         [description]
     */
    public function groupSync($userId,$data = array()){
        return $this->format_array($this->im->groupSync($userId,$data));
    }

    /**
     * 刷新群信息
     * @return [type] [description]
     */
    public function groupRefresh(){
        return $this->format_array($this->im->groupRefresh($groupId,$groupName));
    }

    /**
     * 创建群组，并将用户加入该群组，用户将可以收到该群的消息。注：其实本方法是加入群组方法 /group/join 的别名。
     * @param  [type] $userId    [要加入群的用户 Id。（必传）]
     * @param  [type] $groupId   [要加入的群 Id。（必传）]
     * @param  [type] $groupName [要加入的群 Id 对应的名称。（可选）]
     * @return [type]            [description]
     */
    public function groupCreate($userId,$groupId,$groupName){
        return $this->format_array($this->im->groupCreate($userId,$groupId,$groupName));
    }

    /**
     * 将用户加入指定群组，用户将可以收到该群的消息
     * @param  [type] $userId    [要加入群的用户 Id。（必传）]
     * @param  [type] $groupId   [要加入的群 Id。（必传）]
     * @param  [type] $groupName [要加入的群 Id 对应的名称。（可选）]
     * @return [type]            [description]
     */
    public function groupJoin($userId,$groupId,$groupName){
        return $this->format_array($this->im->groupJoin($userId,$groupId,$groupName));
    }

    /**
     * 将用户从群中移除，不再接收该群组的消息
     * @param  [type] $userId  [要退出群的用户 Id.(必传)]
     * @param  [type] $groupId [要退出的群 Id。（必传）]
     * @return [type]          [description]
     */
    public function groupQuit($userId,$groupId){
        return $this->format_array($this->im->groupQuit($userId,$groupId));
    }

    /**
     * 解散群组方法  将该群解散，所有用户都无法再接收该群的消息。
     * @param  [type] $userId  [操作解散群的用户 Id。（必传）]
     * @param  [type] $groupId [要解散的群 Id。（必传）]
     * @return [type]          [description]
     */
    public function groupDismiss($userId,$groupId){
        return $this->format_array($this->im->groupDismiss($userId,$groupId));
    }

    /**
     * 发送会话消息 (现在为发送单聊消息)
     * @param  [type] $fromUserId  [发送人用户 Id。（必传）]
     * @param  array  $toUserId    [接收用户 Id，提供多个本参数可以实现向多人发送消息。（必传）]
     * @param  [type] $objectName  [消息类型，参考融云消息类型表.消息标志；可自定义消息类型。（必传）]
     * @param  [type] $content     [发送消息内容，参考融云消息类型表.示例说明；如果 objectName 为自定义消息类型，该参数可自定义格式。（必传）]
     * @param  string $pushContent [如果为自定义消息，定义显示的 Push 内容。(可选)]
     * @param  string $pushData    [针对 iOS 平台，Push 通知附加的 payload 字段，字段名为 appData。(可选)]
     * @return [type]              [description]
     */
    public function messagePublish($fromUserId,$toUserId = array(),$objectName,$content,$pushContent='',$pushData = ''){
        return $this->format_array($this->im->messagePublish($fromUserId,$toUserId,$objectName,$content,$pushContent,$pushData));
    }

    /**
     * 以一个用户身份向群组发送消息
     * @param  [type] $fromUserId  [发送人用户 Id。（必传）]
     * @param  array  $toGroupId   [接收群Id，提供多个本参数可以实现向多群发送消息。（必传）]
     * @param  [type] $objectName  [消息类型，参考融云消息类型表.消息标志；可自定义消息类型。（必传）]
     * @param  [type] $content     [发送消息内容，参考融云消息类型表.示例说明；如果 objectName 为自定义消息类型，该参数可自定义格式。（必传）]
     * @param  string $pushContent [如果为自定义消息，定义显示的 Push 内容。(可选)]
     * @param  string $pushData    [针对 iOS 平台，Push 通知附加的 payload 字段，字段名为 appData。(可选)]
     * @return [type]              [description]
     */
    public function messageGroupPublish($fromUserId,$toGroupId = array(),$objectName,$content,$pushContent='',$pushData = ''){
        return $this->format_array($this->im->messageGroupPublish($fromUserId,$toGroupId,$objectName,$content,$pushContent,$pushData));
    }

    /**
     * 一个用户向一个或多个用户发送系统消息 
     * @param  [type] $fromUserId  [发送人用户 Id。（必传）]
     * @param  array  $toUserId    [接收用户Id，提供多个本参数可以实现向多用户发送系统消息。（必传）]
     * @param  [type] $objectName  [消息类型，参考融云消息类型表.消息标志；可自定义消息类型。（必传）]
     * @param  [type] $content     [发送消息内容，参考融云消息类型表.示例说明；如果 objectName 为自定义消息类型，该参数可自定义格式。（必传）]
     * @param  string $pushContent [如果为自定义消息，定义显示的 Push 内容。(可选)]
     * @param  string $pushData    [针对 iOS 平台，Push 通知附加的 payload 字段，字段名为 appData。(可选)]
     * @return [type]              [description]
     */
    public function messageSystemPublish($fromUserId,$toUserId = array(),$objectName,$content,$pushContent='',$pushData = ''){
        return $this->format_array($this->im->messageSystemPublish($fromUserId,$toUserId,$objectName,$content,$pushContent,$pushData));
    }

    /**
     * 某发送消息给一个应用下的所有注册用户。  发送广播消息
     * @param  [type] $fromUserId [发送人用户 Id。（必传）]
     * @param  [type] $objectName [消息类型，参考融云消息类型表.消息标志；可自定义消息类型。（必传）]
     * @param  [type] $content    [发送消息内容，参考融云消息类型表.示例说明；如果 objectName 为自定义消息类型，该参数可自定义格式。（必传）]
     * @return [type]             [description]
     */
    public function messageBroadcast($fromUserId,$objectName,$content){
        return $this->format_array($this->im->messageBroadcast($fromUserId,$objectName,$content));
    }

    /**
     * 一个用户向聊天室发送消息
     * @param $fromUserId 发送人用户 Id。（必传）
     * @param $toChatroomId 接收聊天室Id，提供多个本参数可以实现向多个聊天室发送消息。（必传）
     * @param $objectName 消息类型，参考融云消息类型表.消息标志；可自定义消息类型。（必传）
     * @param $content 发送消息内容，参考融云消息类型表.示例说明；如果 objectName 为自定义消息类型，该参数可自定义格式。（必传）
     */
    public function messageChatroomPublish($fromUserId,$toChatroomId = array(),$objectName,$content){
        return $this->format_array($this->im->messageChatroomPublish($fromUserId,$toChatroomId,$objectName,$content));
    }

    /**
     * 获取 APP 内指定某天某小时内的所有会话消息记录的下载地址
     * @param  [type] $date [指定北京时间某天某小时，格式为：2014010101,表示：2014年1月1日凌晨1点。（必传）]
     * @return [type]       [description]
     */
    public function messageHistory($date){
        return $this->format_array($this->im->messageHistory($date));
    }

    /**
     * 转化成数组
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function format_array($data){
        return $data == false ? false : json_decode($data,true);
    }



    public function sendMsg($value)
    {
        //$all = $this->load('message')->findAllMessageByIsSend();
        //foreach ($all as $key => $value) {
            switch ($value['category']) {
                case '1':
                    //新的朋友
                    $this->sendFriendMsg($value);
                    break;
                case '2':
                case '6':
                    //有道帖子
                    $this->sendNewsMsg($value);
                    break;
                case '3':
                    //群消息
                    $this->sendGroupMsg($value);
                    break;
                case '4':
                    $this->sendPuNiuMsg($value);
                    break;
                case '5':
                    $this->sendInfoNtfMsg($value);
                    break;
            }
        //}
    }

    /**
     * 小灰条
     * @param $data
     */
    public function sendInfoNtfMsg($data){
        $fromUserId = $data['send_id'];
        $groupId = array($data['source_id']);
        $objectName = "RC:InfoNtf";
        $content = '{"message":"'.$data['content'].'","extra":""}';
        $pushContent = "";
        $pushData = "";

        $this->messageGroupPublish($fromUserId,$groupId ,$objectName,$content,$pushContent,$pushData);
    }
    public function sendFriendMsg($data)
    {
        $fromUserId = $data['send_id'];//新的朋友、跑步有道、群组账户
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->convertFriendMessageContent($data)));
        $pushContentDesc = $this->getPushContentDesc($data);
        $content = '{"content":"' . $pushContentDesc . '","extra":"'.$extra.'"}';//添加推送的内容
        $pushContent = "";
        $pushData = "1";
        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        // if($rst){
        //     $this->updateMessage($data['id']);
        // }
    }

    public function sendNewsMsg($data)
    {
        $fromUserId = $data['send_id'];
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->convertNewsMessageContent($data)));
        $pushContentDesc = $this->getPushContentDesc($data);
        $content = '{"content":"' . $pushContentDesc . '","extra":"'.$extra.'"}';
        $pushContent = "$pushContentDesc";//自定义推送消息
        $pushData = "1";

        
        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        // if($rst){
        //     $this->updateMessage($data['id']);
        // }
    }

    public function sendGroupMsg($data)
    {
        $fromUserId = $data['send_id'];
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $extra = base64_encode(json_encode($this->convertGroupMessageContent($data)));
        $pushContentDesc = $this->getPushContentDesc($data);
        $content = '{"content":"' . $pushContentDesc . '","extra":"'.$extra.'"}';//
        $pushContent = "";
        $pushData = "1";
        $rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
        // if($rst){
        //     $this->updateMessage($data['id']);
        // }   
    }

    public function sendPuNiuMsg($data)
    {
        $fromUserId = "175701";//扑妞
        $toUserId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        //$extra = base64_encode(json_encode($this->convertFriendMessageContent($data)));
        $content = '{"content":"'.$data['content'].'","extra":""}';
        $pushContent = "";
        $pushData = "1";

        $this->messagePublish($fromUserId,$toUserId ,$objectName,$content,$pushContent,$pushData);
        //$rst = $this->sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
    }


    public function sendRongCloud($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData){
        return $this->messageSystemPublish($fromUserId, $toUserId, $objectName, $content, $pushContent, $pushData);
    }

    private function updateMessage($id)
    {
        $is_send = 1;
        $array = compact('id','is_send');
        $rst = $this->base->db->updateRowTable('r_message_record', $array);
    }


    /**
     * 发送虎扑妞发送的消息
     * @param  [type] $target_id [description]
     * @param  [type] $content   [description]
     * @return [type]            [description]
     */
    public function sendPuNiuSystemMessage($target_id,$content){
        $category = "4";
        $send_id = "175701";
        $source_id = 0;
        $descType = "";
        $this->insertMessage($category, $send_id ,$source_id ,$target_id ,$descType, $content);
    }


    /**
     * 获取指令消息
     * @return [type] [description]
     */
    public function getInstrMessage(){
        $content = $this->base->redis->hGetAll(REDIS_PREFIX . "Instr");//hash 

        $this->loginfo("getInstrMessage  step 1 = " . var_export($content,true),'message');

        if(!$content){
            $sql = "select * from r_message_instr";
            $instrContent = $this->base->db->getAll($sql);

            $this->loginfo("getInstrMessage  step 2 = " . var_export($instrContent,true),'message');

            $instrArr = array();
            foreach ($instrContent as $key => $item) {
                $instrArr[$item['key']] = $item['content'];
            }

            $this->loginfo("getInstrMessage  step 3 = " . var_export($instrArr,true),'message');

            $this->base->redis->hMset(REDIS_PREFIX . "Instr", $instrArr);
        }
        return $this->base->redis->hGetAll(REDIS_PREFIX . "Instr");
    }

    /**
     * 发送指令触发消息
     * @param  [type] $toUserId   [description]
     * @param  [type] $fromUserId [description]
     * @param  [type] $objectName [description]
     * @param  [type] $content    [description]
     * @return [type]             [description]
     */
    public function sendInstrTriggerMessage($toUserId, $fromUserId, $objectName, $content){

        $this->loginfo("sendInstrTriggerMessage  step 1 = " . $toUserId . ";" . $fromUserId . ";" . $fromUserId . ";" . $objectName . ";" . $content,'message');
        $setArr = array(
            "首次" => "1",
            "GN" => "2",
            "WX" => "3",
            "想" => "4",
            "不想" => "4",
            "其他" => "5",
        );
        //获取当前步骤
        $step = $this->base->redis->get(REDIS_PREFIX . "Instr_step_" . $fromUserId);
        $this->loginfo("sendInstrTriggerMessage  step 2 = " . $step,'message');

        $this->loginfo("sendInstrTriggerMessage  step 2.6 = " . $this->base->uid . ";" . ("175701" == $toUserId) . ";" . ($this->base->uid == $fromUserId ) . ";" . ($objectName == "RC:TxtMsg"),'message');
        //发送触发消息
        if("175701" == $toUserId  && $objectName == "RC:TxtMsg"){

            $cont = json_decode($content,true);
            $cont = $cont['content'];

            $this->loginfo("sendInstrTriggerMessage  step 3 = " . var_export($cont,true),'message');

            $instrArr = $this->getInstrMessage();

            $this->loginfo("sendInstrTriggerMessage  step 4 = " . var_export($instrArr,true),'message');

            if(array_key_exists($cont, $setArr)){

                $this->loginfo("sendInstrTriggerMessage  step 5 = " . var_export($setArr[$cont],true),'message');

                if("1" == $step && "2" == $setArr[$cont]){
                    $this->sendPuNiuSystemMessage($fromUserId,$instrArr[$cont]);
                    $this->base->redis->set(REDIS_PREFIX . "Instr_step_" . $fromUserId, "2");
                }else if("2" == $step && "3" == $setArr[$cont]){
                    $this->sendPuNiuSystemMessage($fromUserId,$instrArr[$cont]);
                    $this->base->redis->set(REDIS_PREFIX . "Instr_step_" . $fromUserId, "3");
                }else if("3" == $step && "4" == $setArr[$cont]){
                    $this->sendPuNiuSystemMessage($fromUserId,$instrArr[$cont]);
                    $this->base->redis->set(REDIS_PREFIX . "Instr_step_" . $fromUserId, "4");
                }else{
                    //$this->sendPuNiuSystemMessage($fromUserId,$instrArr['其他']);
                    //$this->base->redis->set(REDIS_PREFIX . "Instr_step_" . $fromUserId, "5");
                }
            }else{
                //$this->sendPuNiuSystemMessage($fromUserId,$instrArr['其他']);
                //$this->base->redis->set(REDIS_PREFIX . "Instr_step_" . $fromUserId, "5");
            }
        }
    }

}
